﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Data.OracleClient;

namespace XMLToWordLib
{
    /**
     * 说明：
     *       一般书签： tag+编号( tag0101 )
     *   全部加法书签： add+编号1_编号2_编号3( add0101_0102_0103 )
     *   全部减法书签： sub+编号1_编号2_编号3( sub0101_0102_0103 )
     *   全部乘法书签： mul+编号1_编号2_编号3( mul0101_0102_0103 )
     *   全部除法书签： div+编号1_编号2_编号3( div0101_0102_0103 )
     *   
     *   同一编号的 书签： tag+编号+'_'+序号   ( tag0101_1 表示和 tag0101 一样的值) 
     * 
     *   基础信息书签配置： tag+字段名+'_'+序号   ( tag统计数据开始时间_1 表示和 tag统计数据开始时间 一样的值) 
     * */

    //标签中必须以tag开头
    public class MakeWordLib
    {


        public static void TagReplaceToWord(string tagMubanWordPath, string outWordPath, BaseConfig baseConfig)
        {

            Class_WordControler wordControl = new Class_WordControler();
            //数据库连接池
            DBLinkPool dbLinkPool = new DBLinkPool();
            try
            {
                if (System.IO.File.Exists(outWordPath))
                {
                    throw new Exception("生成文件已经存在！"); 
                }
                wordControl.DO_show(tagMubanWordPath);
                wordControl.DO_Doc_SaveAs_HideModeEx(outWordPath);
                //获取WORD中的标签集合
                List<WordTagMan> WordTagMans = wordControl.DO_ReadAllBookMark();
                List<WordTagMan> newWordTagMans = new List<WordTagMan>();
                WordTagMan tempWordTagMan;
                DataTable tjTable = GetConfigTable(baseConfig.connectionString, string.Format(baseConfig.tjTableSQLForMate, GetTagsStr( WordTagMans))).Tables[0];
                string tabTagString;
                int selCount = 0;
                string linkUserID;
                DBLinkUser dbLinkUser;
                int TJNum=0;
                foreach (DataRow dtrow in tjTable.Rows)
                {
                    //查找标签集合中的一个对象
                    tabTagString = "tag" + dtrow[baseConfig.TagFildName].ToString().Trim();
                    var selectPeos = from wordTagMan in WordTagMans
                                     where wordTagMan.BookMarkName == tabTagString
                                     select wordTagMan;
                    selCount=selectPeos.Count<WordTagMan>();
                    if (selCount > 0)
                    {
                        tempWordTagMan = new WordTagMan();
                        tempWordTagMan.BookMarkName = selectPeos.First<WordTagMan>().BookMarkName;
                        

                        //-------查询出统计数据
                        try
                        {
                            linkUserID = dtrow["连接参数编号"].ToString();
                            dbLinkPool.Add(linkUserID, linkUserID, dtrow["连接参数"].ToString());
                            dbLinkUser = dbLinkPool.GetLinkUser(linkUserID);
                            //连接数据库
                            dbLinkUser.Start();
                            TJNum = dbLinkUser.GetTJNum(dtrow["执行语句"].ToString());
                        }
                        catch (Exception ex)
                        {
                            TJNum = int.Parse(dtrow["结果"].ToString());
                        }
                        //-------------------


                        tempWordTagMan.BookMarkText = string.Format(dtrow[baseConfig.forMateFildName].ToString(), TJNum);
                        newWordTagMans.Add(tempWordTagMan);
                       // selectPeos.First<WordTagMan>().BookMarkText = string.Format(dtrow[forMateFildName].ToString(), dtrow["结果"].ToString());
                    }                    
                }
                   


                //如果给定的稳定 无任何  书签 则退出
                if (WordTagMans == null)
                {
                    return;
                }
                //更新数据 后把书签信息更新进WORD中
                wordControl.DO_WriteToBookMark(newWordTagMans);
            }
            catch (Exception ex)
            {
                throw new Exception( ex.Message);
            }
        }

        /// <summary>
        /// 如果是以XML 配置  则根据 xml 的配置来设置
        /// </summary>
        /// <param name="xmlPath"></param>
        /// <param name="tagMubanWordPath"></param>
        /// <param name="outWordPath"></param>
        /// <param name="TagFildName">统计项编号 字段名:"统计项编号"</TagFildName>
        /// <param name="DataLinkIDFild">连接参数编号 字段名:"连接参数编号"</param>
        /// <param name="LinKConStrFild">连接参数 字段名:"连接参数"</param>
        /// <param name="doSqlFild">执行语句 字段名:"执行语句"</param>
        /// <param name="FomateFild">统计描述 字段名:'统计描述'</param>
        /// <param name="ResoultFold">结果 字段名:"结果"</param>
        /// <param name="nowSelete">true 是结果为现查询，否则就利用配置里面的 结果字段值 或者0</param>
        public static void TagReplaceToWord(string xmlPath, string tagMubanWordPath, string outWordPath,string TagFildName, string DataLinkIDFild, string LinKConStrFild, string doSqlFild, string FomateFild, string ResoultFold, bool nowSelete)
        {

            Class_WordControler wordControl = new Class_WordControler(); 
            //数据库连接池
            DBLinkPool dbLinkPool = new DBLinkPool();
            try
            {
                if (System.IO.File.Exists(outWordPath))
                {
                    throw new Exception("生成文件已经存在！");
                }
                wordControl.DO_show(tagMubanWordPath);
                wordControl.DO_Doc_SaveAs_HideModeEx(outWordPath);
                //获取WORD中的标签集合
                List<WordTagMan> WordTagMans = wordControl.DO_ReadAllBookMark();
                //List<WordTagMan> newWordTagMans = new List<WordTagMan>();
                WordTagMan tempWordTagMan;
                DataSet ds = new DataSet();
                ds.ReadXml(xmlPath);
                DataTable tjTable = ds.Tables[BaseConfig.DataTableName];


                //增加配置信息
                DataTable cofTable = ds.Tables[BaseConfig.BaseTableName];
                if (cofTable.Rows.Count > 0)
                {
                    DataRow dr = cofTable.Rows[0];
                    for (int col_i = 0; col_i < cofTable.Columns.Count; col_i++)
                    {
                        DataRow newRow = tjTable.NewRow();
                        newRow[TagFildName] = cofTable.Columns[col_i].ColumnName;
                        newRow[ResoultFold] = dr[col_i].ToString();
                        tjTable.Rows.Add(newRow);
                    }

                }



                string tabTagString;
                int selCount = 0;
                string linkUserID;
                DBLinkUser dbLinkUser;
                string TJNum = "0";
                #region
                foreach (DataRow dtrow in tjTable.Rows)
                {
                    //查找标签集合中的一个对象
                    tabTagString = dtrow[TagFildName].ToString().Trim();
                    var selectPeos = from wordTagMan in WordTagMans
                                     where wordTagMan.BookMarkName == tabTagString
                                     select wordTagMan;
                    selCount = selectPeos.Count<WordTagMan>();


                    if (selCount > 0)
                    {

                        // tempWordTagMan = new WordTagMan();
                        //tempWordTagMan.BookMarkName = selectPeos.First<WordTagMan>().BookMarkName;

                        foreach (var oneobj in selectPeos)
                        {
                            tempWordTagMan = oneobj as WordTagMan;

                            if (tempWordTagMan.BookMarkID == "tag0501030102")
                            {
                                int tttt = 0;
                            }

                            if (nowSelete && DataLinkIDFild != null && LinKConStrFild != null && doSqlFild != null)
                            {
                                ////-------查询出统计数据
                                try
                                {
                                    linkUserID = dtrow[DataLinkIDFild].ToString();
                                    dbLinkPool.Add(linkUserID, linkUserID, dtrow[LinKConStrFild].ToString());
                                    dbLinkUser = dbLinkPool.GetLinkUser(linkUserID);
                                    //连接数据库
                                    dbLinkUser.Start();
                                    TJNum = dbLinkUser.GetTJNum(dtrow[doSqlFild].ToString()).ToString();
                                }
                                catch (Exception ex)
                                {
                                    TJNum = dtrow[ResoultFold].ToString();
                                }

                            }

                            try//if (ResoultFold != null && ResoultFold.Length > 0)                            
                            {
                                TJNum = dtrow[ResoultFold].ToString();
                            }
                            catch
                            {
                                throw new Exception("结果字段配置错误！");
                            }
                            try
                            {
                                tempWordTagMan.BookMarkText = string.Format(dtrow[FomateFild].ToString(), TJNum);
                            }
                            catch
                            {
                                tempWordTagMan.BookMarkText = TJNum;
                            }

                        }

                    }
                }

                #endregion

                
               

                //如果给定的稳定 无任何  书签 则退出
                if (WordTagMans == null)
                {
                    return;
                }

                try
                {
                    WordTagMansMact(WordTagMans);
                }
                catch
                {
                    throw new Exception("部分运算书签设置错误！");
                }
                finally
                {
                    //更新数据 后把书签信息更新进WORD中
                    wordControl.DO_WriteToBookMark(WordTagMans);
                    //保存
                    wordControl.DO_Doc_SaveAs_defualtMode(outWordPath);
                    //DO_Doc_SaveAs_HideModeEx
                    //DO_Doc_SaveAs_HideMode(string filepath)
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static void TagReplaceToWord(string xmlPath, string tagMubanWordPath, string outWordPath)
        { 
           BaseConfig congif =new BaseConfig(null);
           TagReplaceToWord(xmlPath, tagMubanWordPath, outWordPath, congif.TagFildName, congif.DataLinkIDFild, congif.DBConFildName, congif.DoSqlFild, congif.FomateFild, congif.ResoultFold, false);                   
        }

        /// <summary>
        /// 书签集合的特殊处理，比如 有的标签为空，或有的标签为其他标签之和
        /// </summary>
        /// <param name="WordTagMans"></param>
        static void WordTagMansMact(List<WordTagMan> WordTagMans)
        {
            int ResNum = 0;
            int i = 0;
            WordTagMan tempMan;
            int selCount = 0;
            string TempBookMarkID;
            foreach (WordTagMan wordTagMan in WordTagMans)
            {
                
                string  []chidIDStrs=null;
                if (wordTagMan.Type == "add" || wordTagMan.Type == "mul" || wordTagMan.Type == "sub" || wordTagMan.Type == "div")
                {
                    chidIDStrs = wordTagMan.BookMarkName.Split('_');
                    i = 0;
                    foreach (string str in chidIDStrs)
                    {
                        TempBookMarkID = "tag" + str;
                        var selectPeos = from _wordTagMan in WordTagMans
                                         where _wordTagMan.BookMarkID == TempBookMarkID
                                         select _wordTagMan;
                        selCount = selectPeos.Count<WordTagMan>();
                        if (selCount > 0)
                        {
                            tempMan = selectPeos.First<WordTagMan>();
                            if(wordTagMan.Type == "add")
                            {
                                ResNum += Convert.ToInt32(tempMan.BookMarkText);
                            }
                            else if (wordTagMan.Type == "mul")
                            {
                                if (i == 0)
                                {
                                    ResNum = Convert.ToInt32(tempMan.BookMarkText);
                                }
                                else
                                {
                                    ResNum *= Convert.ToInt32(tempMan.BookMarkText);
                                }
                            }
                            else if (wordTagMan.Type == "sub")
                            {
                                if (i == 0)
                                {
                                    ResNum = Convert.ToInt32(tempMan.BookMarkText);
                                }
                                else
                                {
                                    ResNum -= Convert.ToInt32(tempMan.BookMarkText);
                                }
                            }
                            else if (wordTagMan.Type == "div")
                            {
                                if (i == 0)
                                {
                                    ResNum = Convert.ToInt32(tempMan.BookMarkText);
                                }
                                else
                                {
                                    ResNum /= Convert.ToInt32(tempMan.BookMarkText);
                                }
                            }
                        }
                        i++;

                    }
                    
                    
                    wordTagMan.BookMarkText = ResNum.ToString(); 
                }
            }
        
        }

        #region 根据List 获取 标签集合字符串  如： '0101','0202'
        private static string GetTagsStr(List<WordTagMan> WordTagMans)
        {
            //书签结合字符串
            StringBuilder tagS = new StringBuilder();
            foreach (WordTagMan wordTagMan in WordTagMans)
            {
                if (wordTagMan != null)
                {
                    tagS.Append(string.Format("'{0}',", wordTagMan.BookMarkName.Substring(3, wordTagMan.BookMarkName.Length - 3)));
                }
            }
            string tagsStr = tagS.ToString();
            return tagsStr.Substring(0, tagsStr.Length - 1);

        }
        #endregion

        #region  数据库操作

        public static DataSet GetConfigTable(string connectionString, string SQLString)
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    OracleDataAdapter command = new OracleDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch ( Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }	
        }


        #endregion

    }


    public class OraDBHelper
    { 
        
    
    
    }


}
